<?php
/**
 * WooCommerce Configuration Application
 * WooCommerce配置应用文件
 * 
 * @package WP Bootstrap Woo
 */

if (!defined('ABSPATH')) {
    exit; // 禁止直接访问
}

/**
 * 应用WooCommerce基本设置
 */
function wbw_apply_woocommerce_settings() {
    // 商店布局设置
    if (_xin('shop_columns')) {
        add_filter('loop_shop_columns', function() {
            return intval(_xin('shop_columns', 4));
        });
    }
    
    // 每页产品数量
    if (_xin('products_per_page')) {
        add_filter('loop_shop_per_page', function() {
            return intval(_xin('products_per_page', 12));
        });
    }
    
    // 购物车跳转设置
    if (_xin('cart_redirect_after_add', false)) {
        add_filter('woocommerce_add_to_cart_redirect', function() {
            return wc_get_cart_url();
        });
    }
    
    // 游客结账设置
    if (_xin('enable_guest_checkout', true)) {
        add_filter('woocommerce_checkout_must_be_logged_in', '__return_false');
    }
    
    // 结账创建账户设置
    if (_xin('checkout_create_account', false)) {
        add_filter('woocommerce_checkout_registration_enabled', '__return_true');
    }
}
add_action('init', 'wbw_apply_woocommerce_settings');

/**
 * 移除或添加WooCommerce默认功能
 */
function wbw_customize_woocommerce_features() {
    // 相关产品
    if (!_xin('show_related_products', true)) {
        remove_action('woocommerce_output_related_products_args', 'woocommerce_output_related_products');
    } else {
        add_filter('woocommerce_output_related_products_args', function($args) {
            $args['posts_per_page'] = intval(_xin('related_products_count', 4));
            return $args;
        });
    }
    
    // 向上销售产品
    if (!_xin('show_upsell_products', true)) {
        remove_action('woocommerce_output_upsells', 'woocommerce_output_upsells');
    }
    
    // 交叉销售产品
    if (!_xin('enable_cart_cross_sells', true)) {
        remove_action('woocommerce_cart_collaterals', 'woocommerce_cross_sell_display');
    }
    
    // 结账优惠券
    if (!_xin('enable_checkout_coupons', true)) {
        remove_action('woocommerce_before_checkout_form', 'woocommerce_checkout_coupon_form', 10);
    }
}
add_action('wp', 'wbw_customize_woocommerce_features');

/**
 * 自定义WooCommerce邮件设置
 */
function wbw_custom_woocommerce_email_settings() {
    // 自定义发件人名称
    $from_name = _xin('custom_email_from_name');
    if ($from_name) {
        add_filter('wp_mail_from_name', function() use ($from_name) {
            return $from_name;
        });
    }
    
    // 自定义发件人邮箱
    $from_email = _xin('custom_email_from_address');
    if ($from_email && is_email($from_email)) {
        add_filter('wp_mail_from', function() use ($from_email) {
            return $from_email;
        });
    }
}
add_action('init', 'wbw_custom_woocommerce_email_settings');

/**
 * 订单确认邮件抄送
 */
function wbw_order_confirmation_cc($recipient, $order) {
    $cc_emails = _xin('order_confirmation_cc');
    if ($cc_emails) {
        $cc_array = array_map('trim', explode(',', $cc_emails));
        $cc_array = array_filter($cc_array, 'is_email');
        if (!empty($cc_array)) {
            $recipient .= ',' . implode(',', $cc_array);
        }
    }
    return $recipient;
}
add_filter('woocommerce_email_recipient_new_order', 'wbw_order_confirmation_cc', 10, 2);

/**
 * 库存不足通知
 */
function wbw_check_stock_notifications() {
    if (!_xin('enable_stock_notifications', true)) {
        return;
    }
    
    $threshold = intval(_xin('stock_notification_threshold', 5));
    
    $args = array(
        'post_type' => 'product',
        'post_status' => 'publish',
        'meta_query' => array(
            array(
                'key' => '_manage_stock',
                'value' => 'yes'
            ),
            array(
                'key' => '_stock',
                'value' => $threshold,
                'compare' => '<='
            )
        )
    );
    
    $low_stock_products = get_posts($args);
    
    if (!empty($low_stock_products)) {
        foreach ($low_stock_products as $product_post) {
            $product = wc_get_product($product_post->ID);
            $stock_quantity = $product->get_stock_quantity();
            
            // 发送库存不足通知
            wbw_send_stock_notification($product, $stock_quantity);
        }
    }
}

/**
 * 发送库存不足通知邮件
 */
function wbw_send_stock_notification($product, $stock_quantity) {
    $admin_email = get_option('admin_email');
    $subject = sprintf('[%s] Low Stock Alert - %s', get_bloginfo('name'), $product->get_name());
    
    $message = sprintf(
        "Product: %s\nSKU: %s\nCurrent Stock: %d\nProduct URL: %s\n\nPlease restock this product as soon as possible.",
        $product->get_name(),
        $product->get_sku(),
        $stock_quantity,
        get_permalink($product->get_id())
    );
    
    wp_mail($admin_email, $subject, $message);
}

/**
 * 定期检查库存（每日一次）
 */
if (!wp_next_scheduled('wbw_daily_stock_check')) {
    wp_schedule_event(time(), 'daily', 'wbw_daily_stock_check');
}
add_action('wbw_daily_stock_check', 'wbw_check_stock_notifications');

/**
 * 新订单管理员通知
 */
function wbw_new_order_admin_notification($order_id) {
    if (!_xin('enable_new_order_admin_notification', true)) {
        return;
    }
    
    $order = wc_get_order($order_id);
    if (!$order) {
        return;
    }
    
    $admin_email = get_option('admin_email');
    $subject = sprintf('[%s] New Order #%s', get_bloginfo('name'), $order->get_order_number());
    
    $message = sprintf(
        "A new order has been placed.\n\nOrder Number: %s\nOrder Date: %s\nCustomer: %s %s\nEmail: %s\nTotal: %s\n\nView Order: %s",
        $order->get_order_number(),
        $order->get_date_created()->format('Y-m-d H:i:s'),
        $order->get_billing_first_name(),
        $order->get_billing_last_name(),
        $order->get_billing_email(),
        $order->get_formatted_order_total(),
        admin_url('post.php?post=' . $order_id . '&action=edit')
    );
    
    wp_mail($admin_email, $subject, $message);
}
add_action('woocommerce_thankyou', 'wbw_new_order_admin_notification');

/**
 * 商店侧边栏设置
 */
function wbw_shop_sidebar_settings() {
    if (!_xin('enable_shop_sidebar', true)) {
        // 移除商店侧边栏
        remove_action('woocommerce_sidebar', 'woocommerce_get_sidebar', 10);
    }
}
add_action('wp', 'wbw_shop_sidebar_settings');

/**
 * 获取商店侧边栏位置
 */
function wbw_get_shop_sidebar_position() {
    return _xin('shop_sidebar_position', 'left');
}

/**
 * 产品图片设置
 */
function wbw_product_image_settings() {
    // 图片放大镜
    if (!_xin('product_image_zoom', true)) {
        remove_theme_support('wc-product-gallery-zoom');
    }
    
    // 图片灯箱
    if (!_xin('product_image_lightbox', true)) {
        remove_theme_support('wc-product-gallery-lightbox');
    }
}
add_action('after_setup_theme', 'wbw_product_image_settings', 20);

/**
 * 获取条款和条件页面URL
 */
function wbw_get_terms_page_url() {
    $terms_page_id = _xin('checkout_terms_page');
    if ($terms_page_id) {
        return get_permalink($terms_page_id);
    }
    return '';
}

/**
 * 在结账页面添加条款和条件
 */
function wbw_checkout_terms_and_conditions() {
    $terms_url = wbw_get_terms_page_url();
    if ($terms_url) {
        echo '<div class="checkout-terms">';
        echo '<p><input type="checkbox" name="terms_agreement" id="terms_agreement" required>';
        echo '<label for="terms_agreement">';
        echo sprintf('I agree to the <a href="%s" target="_blank">Terms and Conditions</a>', esc_url($terms_url));
        echo '</label></p>';
        echo '</div>';
    }
}
add_action('woocommerce_checkout_terms_and_conditions', 'wbw_checkout_terms_and_conditions');

/**
 * 验证条款和条件同意
 */
function wbw_validate_checkout_terms() {
    $terms_url = wbw_get_terms_page_url();
    if ($terms_url && !isset($_POST['terms_agreement'])) {
        wc_add_notice('Please agree to the Terms and Conditions to proceed.', 'error');
    }
}
add_action('woocommerce_checkout_process', 'wbw_validate_checkout_terms');

/**
 * 迷你购物车设置
 */
function wbw_mini_cart_settings() {
    if (!_xin('enable_mini_cart', true)) {
        // 移除迷你购物车相关功能
        remove_action('wp_enqueue_scripts', 'woocommerce_maybe_define_constant');
    }
}
add_action('init', 'wbw_mini_cart_settings');

/**
 * 检查是否启用迷你购物车
 */
function wbw_is_mini_cart_enabled() {
    return _xin('enable_mini_cart', true);
}

/**
 * WooCommerce功能开关检查函数
 */
function wbw_is_ajax_cart_enabled() {
    return _xin('enable_ajax_cart', true);
}

function wbw_is_wishlist_enabled() {
    return _xin('enable_wishlist', true);
}

function wbw_is_product_compare_enabled() {
    return _xin('enable_product_compare', true);
}

function wbw_is_quick_view_enabled() {
    return _xin('enable_quick_view', true);
}